<template>
  <div class="order">
    <!-- 订单页面头部 -->
    <div class="order-header">
      <div class="order-header-content">
        <p>我的订单</p>
      </div>
    </div>

    <!-- 订单内容区域 -->
    <div class="order-content" v-if="orders.length > 0">
      <div class="content" v-for="(item, index) in orders" :key="index">
        <ul>
          <!-- 订单头部信息 -->
          <li class="order-info">
            <div class="order-time">
              <span class="time-label">下单时间：</span>
              <span class="time-value">{{
                formatTime(item[0].order_time)
              }}</span>
              <span class="order-sn">订单号：{{ item[0].order_id }}</span>
            </div>
            <div
              class="order-status"
              :class="getStatusClass(item[0].order_status)"
            >
              {{ getStatusText(item[0].order_status) }}
            </div>
          </li>

          <!-- 商品列表 -->
          <li class="product-list" v-for="(product, i) in item" :key="i">
            <div class="product-item">
              <div class="product-img">
                <router-link
                  :to="{
                    path: '/goods/details',
                    query: { productID: product.product_id },
                  }"
                >
                  <img
                    :src="$target + product.product_picture"
                    :alt="product.product_name"
                  />
                </router-link>
              </div>
              <div class="product-info">
                <div class="product-name">
                  <router-link
                    :to="{
                      path: '/goods/details',
                      query: { productID: product.product_id },
                    }"
                  >
                    {{ product.product_name }}
                  </router-link>
                </div>
                <div class="product-price">
                  <span class="price">¥{{ product.product_price }}</span>
                  <span class="count">x{{ product.product_num }}</span>
                </div>
              </div>
            </div>
          </li>

          <!-- 订单底部信息 -->
          <li class="order-footer">
            <div class="order-total">
              <span class="total-label">实付款：</span>
              <span class="total-price"
                >¥{{ total[index].totalPrice.toFixed(2) }}</span
              >
            </div>
            <div class="order-buttons">
              <el-button
                v-if="item[0].order_status === 0"
                type="primary"
                size="small"
                class="pay-button"
                @click="goToPay(item[0].order_id)"
                >立即付款</el-button
              >
              <el-button
                v-if="item[0].order_status === 0"
                type="text"
                size="small"
                @click="cancelOrder(item[0].order_id)"
                >取消订单</el-button
              >
            </div>
          </li>
        </ul>
      </div>
    </div>

    <!-- 空订单提示 -->
    <div v-else class="order-empty">
      <div class="empty">
        <h2>您还没有订单！</h2>
        <p>快去购物吧！</p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.order {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 20px 0;
}

.order-header {
  background-color: #fff;
  border-bottom: 2px solid #e1251b;
  margin-bottom: 20px;
}

.order-header-content {
  width: 1225px;
  margin: 0 auto;
  padding: 20px 0;
}

.order-header p {
  font-size: 20px;
  color: #333;
  font-weight: bold;
}

.content {
  width: 1225px;
  margin: 0 auto 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.order-info {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-time {
  color: #666;
  font-size: 14px;
}

.time-label {
  color: #999;
}

.order-sn {
  margin-left: 20px;
  color: #666;
}

.order-status {
  font-size: 14px;
  font-weight: 500;
}

.status-pending {
  color: #e1251b;
}

.status-paid {
  color: #67c23a;
}

.status-completed {
  color: #909399;
}

.status-cancelled {
  color: #909399;
}

.product-list {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.product-item {
  display: flex;
  align-items: center;
}

.product-img {
  width: 80px;
  height: 80px;
  margin-right: 20px;
}

.product-img img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
}

.product-name a {
  color: #333;
  text-decoration: none;
}

.product-name a:hover {
  color: #e1251b;
}

.product-price {
  color: #999;
  font-size: 12px;
}

.price {
  color: #e1251b;
  font-weight: bold;
  margin-right: 8px;
}

.order-footer {
  padding: 16px 20px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  background-color: #fafafa;
}

.order-total {
  margin-right: 20px;
}

.total-label {
  color: #999;
  font-size: 14px;
}

.total-price {
  color: #e1251b;
  font-size: 18px;
  font-weight: bold;
}

.order-buttons {
  display: flex;
  gap: 12px;
}

.pay-button {
  background-color: #e1251b;
  border-color: #e1251b;
}

.pay-button:hover {
  background-color: #c81623;
  border-color: #c81623;
}

.order-empty {
  width: 1225px;
  margin: 0 auto;
  background-color: #fff;
  border-radius: 4px;
  padding: 40px;
  text-align: center;
}

.empty h2 {
  font-size: 20px;
  color: #333;
  margin-bottom: 16px;
}

.empty p {
  color: #999;
  font-size: 14px;
}
</style>

<script>
export default {
  data() {
    return {
      orders: [],
      total: [],
    };
  },
  activated() {
    this.getOrders();
  },
  methods: {
    // 获取订单数据
    getOrders() {
      this.$axios
        .post("/api/order/list", {
          user_id: this.$store.getters.getUser.user_id,
        })
        .then((res) => {
          if (res.data.code === "001") {
            // 对订单按时间降序排序
            this.orders = res.data.data.sort((a, b) => {
              return b[0].order_time - a[0].order_time;
            });
          } else {
            this.notifyError(res.data.msg);
          }
        })
        .catch((err) => {
          return Promise.reject(err);
        });
    },

    // 格式化时间
    formatTime(timestamp) {
      const date = new Date(timestamp);
      return date.toLocaleString("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit",
        hour12: false,
      });
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: "等待付款",
        1: "已付款",
        2: "交易完成",
        3: "已取消",
      };
      return statusMap[status] || "未知状态";
    },

    // 获取状态样式类
    getStatusClass(status) {
      const classMap = {
        0: "status-pending",
        1: "status-paid",
        2: "status-completed",
        3: "status-cancelled",
      };
      return classMap[status] || "";
    },

    // 去支付
    goToPay(orderId) {
      this.$router.push({
        path: "/confirmOrder",
        query: { orderId: orderId },
      });
    },

    // 取消订单
    cancelOrder(orderId) {
      this.$confirm("确认取消订单吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 调用取消订单接口
          this.$axios
            .post("/api/order/cancel", {
              order_id: orderId,
            })
            .then((res) => {
              if (res.data.code === "001") {
                this.$message.success("订单已取消");
                this.getOrders(); // 刷新订单列表
              } else {
                this.$message.error(res.data.msg || "取消失败");
              }
            });
        })
        .catch(() => {});
    },
  },
  watch: {
    orders: {
      handler(val) {
        let total = [];
        for (let i = 0; i < val.length; i++) {
          const element = val[i];
          let totalNum = 0;
          let totalPrice = 0;
          for (let j = 0; j < element.length; j++) {
            const temp = element[j];
            totalNum += temp.product_num;
            totalPrice += temp.product_price * temp.product_num;
          }
          total.push({ totalNum, totalPrice });
        }
        this.total = total;
      },
      immediate: true,
    },
  },
};
</script>